#!/bin/bash

# Script to kill all running gollect trode instances
# Usage: ./kill_trodes.sh

# PID file that contains trode PIDs
PID_FILE="trode_pids.txt"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}Stopping all gollect trode instances...${NC}"

# Check if PID file exists
if [ ! -f "$PID_FILE" ]; then
    echo -e "${YELLOW}No PID file found. Looking for trode processes...${NC}"
    
    # Try to find and kill trode processes
    pids=$(pgrep -f "trode")
    if [ -z "$pids" ]; then
        echo -e "${GREEN}No trode processes found.${NC}"
        exit 0
    fi
    
    echo -e "${YELLOW}Found trode processes: $pids${NC}"
    for pid in $pids; do
        echo -e "${YELLOW}Killing process $pid...${NC}"
        kill $pid 2>/dev/null
        if [ $? -eq 0 ]; then
            echo -e "${GREEN}Successfully killed process $pid${NC}"
        else
            echo -e "${RED}Failed to kill process $pid${NC}"
        fi
    done
else
    # Read PIDs from file and kill them
    if [ ! -s "$PID_FILE" ]; then
        echo -e "${YELLOW}PID file is empty. No trodes to kill.${NC}"
        exit 0
    fi
    
    echo -e "${YELLOW}Reading PIDs from $PID_FILE...${NC}"
    
    killed_count=0
    while IFS= read -r pid; do
        if [ -n "$pid" ]; then
            echo -e "${YELLOW}Killing trode process $pid...${NC}"
            
            # Check if process still exists
            if kill -0 "$pid" 2>/dev/null; then
                kill "$pid"
                if [ $? -eq 0 ]; then
                    echo -e "${GREEN}Successfully killed process $pid${NC}"
                    ((killed_count++))
                else
                    echo -e "${RED}Failed to kill process $pid${NC}"
                fi
            else
                echo -e "${YELLOW}Process $pid is no longer running${NC}"
            fi
        fi
    done < "$PID_FILE"
    
    echo -e "${GREEN}Killed $killed_count trode processes${NC}"
fi

# Clean up PID file
if [ -f "$PID_FILE" ]; then
    rm "$PID_FILE"
    echo -e "${BLUE}Removed PID file: $PID_FILE${NC}"
fi

# Clean up config files
echo -e "${BLUE}Cleaning up temporary config files...${NC}"
rm -f trode/config_*.yaml 2>/dev/null

# Clean up log files
echo -e "${BLUE}Cleaning up log files...${NC}"
rm -f trode/trode_*.log 2>/dev/null

echo -e "${GREEN}All gollect trodes stopped and cleaned up!${NC}" 